package com.mg.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mg.common.Constants;
import com.mg.dto.RechargeRecordDto;
import com.mg.dto.SimpleResult;
import com.mg.mapper.RechargeRecordMapper;
import com.mg.mapper.UserMapper;
import com.mg.model.RechargeRecord;
import com.mg.model.User;
import com.mg.service.RechargeRecordService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * Created by mg1213 on 2018/3/18.
 */
@Service
public class RechargeRecordServiceImpl implements RechargeRecordService {
    @Autowired
    private RechargeRecordMapper rechargeRecordMapper;
    @Autowired
    private UserMapper userMapper;

    private Logger logger = LogManager.getLogger(RechargeRecordServiceImpl.class.getName());

    @Override
    public PageInfo<RechargeRecordDto> selectPageInfo(RechargeRecordDto rechargeRecordDto, int start, int limit) {
        PageHelper.offsetPage(start, limit);
        if (rechargeRecordDto.getState() != null && Constants.ALL_STRING.equals(rechargeRecordDto.getState())) {
            rechargeRecordDto.setState(null);
        }
        List<RechargeRecordDto> resultList = rechargeRecordMapper.selectPageInfo(rechargeRecordDto);
        PageInfo<RechargeRecordDto> result = new PageInfo<>(resultList);
        return result;
    }

    @Override
    public SimpleResult insertRechargeRecord(RechargeRecord record) {
        SimpleResult result = new SimpleResult();
        try {
            record.setRechargeTime(new Date());
            rechargeRecordMapper.insert(record);
            result.setObject(record);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("新增充值信息失败 系统未知异常");
            logger.error("新增充值信息失败 系统未知异常", e);
        }
        return result;
    }

    @Override
    public SimpleResult updateRechargeRecord(RechargeRecord record) {
        SimpleResult result = new SimpleResult();
        try {
            RechargeRecord record1 = new RechargeRecord();
            record1.setId(record.getId());
            record1 = rechargeRecordMapper.selectOne(record1);
            if (record1 == null) {
                result.setSuccess(false);
                result.setMsg("该充值信息不存在，请刷新重试！");
            } else {
                if (Constants.RECHARGE_SUCCESS.equals(record.getState()) && !record1.getState().equals(record.getState())) {
                    User user = new User();
                    user.setId(record1.getUserId());
                    user = userMapper.selectOne(user);
                    if (user == null) {
                        result.setSuccess(false);
                        result.setMsg("更新充值充值信息失败，用户信息不存在");
                        return result;
                    } else {
                        BigDecimal balance = user.getBalance();
                        if (balance == null) {
                            balance = new BigDecimal(0.00);
                        }
                        BigDecimal electricityFee = user.getElectricityFee();
                        if (electricityFee.compareTo(BigDecimal.valueOf(0.00D)) > 0) {
                            if (electricityFee.compareTo(record.getAmount()) > 0) {
                                electricityFee = electricityFee.subtract(record.getAmount());
                            } else {
                                balance = balance.add((record.getAmount().subtract(electricityFee)));
                                electricityFee = BigDecimal.valueOf(0.00D);
                            }
                        } else {
                            balance = balance.add(record.getAmount());
                            electricityFee = BigDecimal.valueOf(0.00D);
                        }
                        user.setElectricityFee(electricityFee);
                        user.setBalance(balance);
                        userMapper.updateByPrimaryKeySelective(user);
                    }
                }
                if (Constants.RECHARGE_SUCCESS.equals(record1.getState()) && !record1.getState().equals(record.getState())) {
                    User user = new User();
                    user.setId(record1.getUserId());
                    user = userMapper.selectOne(user);
                    if (user == null) {
                        result.setSuccess(false);
                        result.setMsg("更新充值信息失败，用户信息不存在");
                        return result;
                    } else {
                        BigDecimal balance = user.getBalance();
                        if (balance == null) {
                            balance = new BigDecimal(0.00);
                        }
                        balance = balance.subtract(record.getAmount());
                        user.setBalance(balance);
                        userMapper.updateByPrimaryKeySelective(user);
                    }
                }
                record.setUpdateTime(new Date());
                rechargeRecordMapper.updateByPrimaryKeySelective(record);
            }

        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("更新充值信息失败 系统未知异常");
            logger.error("更新充值信息失败 系统未知异常", e);
        }
        return result;
    }

    @Override
    public SimpleResult deleteRechargeRecord(String ids) {
        SimpleResult result = new SimpleResult();
        try {
            String[] idArr = ids.split(",");
            for (String id : idArr) {

                rechargeRecordMapper.deleteByPrimaryKey(Integer.parseInt(id));
            }
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("删除充值信息失败 系统未知异常");
            logger.error("删除充值信息失败 系统未知异常", e);
        }
        return result;
    }
}
